#include "datagrabber.h"
#include <cmath>
#include "Control/config.h"

QFile file("./bimos-out.txt");
QTextStream out(&file);

/**
 * @brief DataGrabber::DataGrabber
 * @param boxHandle
 */
/**
 * DEFINE DEBUG!!!
 */
#define DEBUG 0
double debugcounter = 0;

DataGrabber::DataGrabber(ulong boxHandle) {

    handle = boxHandle;
    file.open(QIODevice::WriteOnly | QIODevice::Text);

    // initialize ringbuffer
    for (int j = 0; j < SENSOR_COUNT; j++) {
        for (int i = 0; i < ringBufferSize; i++) {
            averageRingBuffer[j][i] = 0;
        }
    }
    // initialize ringBufferPointer
    for (int i = 0; i < SENSOR_COUNT; i++) {
        ringBufferPtr[i] = 0;
    }

}

void DataGrabber::shot() {
        grabVolt();
}

double DataGrabber::getSampleAverage(int ordinal) {
    double sum = 0;
    for (int i = 0; i < ringBufferSize; i++) {
        sum += averageRingBuffer[ordinal][i] ;
    }
    sum /= (double) ringBufferSize;

    return sum;
}

void DataGrabber::saveAverageSamples(int ordinal,double value) {
    // Exceeded size --> reset pointer and save data!
    if (ringBufferPtr[ordinal] >= ringBufferSize) {
        out << ordinal << "\t" << getSampleAverage(ordinal) << "\n";
        out.flush();
        ringBufferPtr[ordinal] = 0;
        // set the first value
        averageRingBuffer[ordinal][ringBufferPtr[ordinal]] = value;
        ringBufferPtr[ordinal]++;
    // Not exceeded size --> save current value in array
    } else {
        averageRingBuffer[ordinal][ringBufferPtr[ordinal]] = value;
        ringBufferPtr[ordinal]++;
    }




}

void DataGrabber::grabVolt() {
    if (DEBUG == 0) {
        for (int i = 0; i < SENSOR_COUNT; i++) {
            double value = DapiADGetVolt(handle,i);
            //saveAverageSamples(i,value);
            emit newValue(i,value);
        }
        emit grabFinished();
    } else {
        for (int i = 0; i < SENSOR_COUNT; i++) {
            double value = fabs(cos(debugcounter/(3*i))+i);
            //saveAverageSamples(i,value);
            emit newValue(i,value);
        }
        debugcounter++;
        emit grabFinished();
    }
    // get absoult
    if (DEBUG == 0) {
        emit newValue(SENSOR_TEMPERATUR_ORDINAL, DapiADGetVolt(handle,SENSOR_TEMPERATUR_ORDINAL));
        emit newValue(SENSOR_ABSOLUTE_ORDINAL, DapiADGetVolt(handle,SENSOR_ABSOLUTE_ORDINAL));
     } else
        emit newValue(SENSOR_ABSOLUTE_ORDINAL, 2.6);
}
